package cn.patpang.core.framework.spring;

import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateEditor extends PropertyEditorSupport {

	private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");
	private static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private DateFormat dateFormat;
	private boolean allowEmpty = true;

	public DateEditor() {
	}

	public DateEditor(DateFormat dateFormat) {
		super();
		this.dateFormat = dateFormat;
	}

	public DateEditor(DateFormat dateFormat, boolean allowEmpty) {
		super();
		this.dateFormat = dateFormat;
		this.allowEmpty = allowEmpty;
	}

	@Override
	public void setAsText(String text) {

		if (this.allowEmpty && !StringUtils.isNotBlank(text)) {
			setValue(null);
		} else {
			try {
				if (null != this.dateFormat) {
					setValue(TIMEFORMAT.parse(text));
				} else {
					if (text.contains(":")) {
						setValue(TIMEFORMAT.parse(text));
					} else {
						setValue(DATEFORMAT.parse(text));
					}
				}
			} catch (ParseException e) {
				setValue(null);
			}
		}
	}

	@Override
	public String getAsText() {
		Date value = (Date) getValue();
		DateFormat dateFormat = this.dateFormat;
		if (null == dateFormat) {
			dateFormat = TIMEFORMAT;
		}
		return value != null ? dateFormat.format(value) : dateFormat.format(new Date());
	}
}